Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Google Medium
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: Unique Length-3 Palindromic Subsequences

Problem Statement

Given a string s, return the total number of unique palindromes of length 3 which are subsequences of s. Even if multiple ways exist to obtain the same subsequence, it is still only counted once.

A palindrome string is a sequence of characters that reads the same backward as forward.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Examples

Example 1:

  • Input: s = "abcba"
  • Expected Output: 3
  • Justification: The three unique length-3 palindromic subsequences are "aba", "aca", and "bcb".

Example 2:

  • Input: s = "aba"
  • Expected Output: 1
  • Justification: The one unique length-3 palindromic subsequence is "aba".

Example 3:

  • Input: s = "aacbbcacb"
  • Expected Output: 9
  • Justification: The nine unique length-3 palindromic subsequences are "aaa", "aca", "aba", "ccc", "cbc", "bbb", "bab", "cac", and "bcb".

Solution

To solve this problem, we will utilize a combination of hashing and set operations to track the unique palindromic subsequences efficiently. The core idea revolves around identifying all the distinct characters that can act as the middle character of a length-3 palindrome and finding if there are corresponding matching characters on either side of each occurrence of this middle character. This approach is effective because it directly targets the structure of the problem — leveraging the fact that for a sequence to be a palindrome of length 3, the first and third characters must be the same, with any character in between.

The algorithm's efficiency comes from minimizing the search space to only those characters that could potentially form a palindrome, rather than exhaustively checking every possible subsequence combination. By doing so, we significantly reduce computational complexity while ensuring that no potential palindrome is overlooked.

Step-by-Step Algorithm

  1. Initialize a Set: Start by creating an empty set, uniquePalindromes, which will store all unique palindromic subsequences of length 3 found in the input string.

  2. Iterate Over Alphabet: Loop through all lowercase English letters ('a' to 'z'). For each character, c, perform the following steps:

    • Find First and Last Occurrences: Determine the first and last positions of c in the input string, s, using indexOf and lastIndexOf methods (or their equivalents in other languages). Let's denote these positions as first and last, respectively.
    • Check for Validity: Ensure that first is less than last. This condition confirms that there are characters between the first and last occurrences of c, which is necessary for forming a palindrome of length 3.
    • Explore Middle Characters: If the above condition holds, iterate over the substring of s that lies between first and last (exclusive). For each character, m, in this substring:
      • Form Palindrome: Construct a palindromic subsequence by placing m between two cs (i.e., cmc).
      • Add to Set: Add this palindromic subsequence to uniquePalindromes set.
  3. Return Result: After completing the above steps for every letter in the alphabet, the size of uniquePalindromes set represents the total number of unique palindromic subsequences of length 3 in the input string. Return this count as the final result.

Algorithm Walkthrough

Let's consider the input: s = "aacbbcacb".

  1. Initialize uniquePalindromes Set: An empty set that will hold all unique length-3 palindromic subsequences found in the string.

  2. Iterate Over Alphabet to Find Unique Palindromes:

    • For 'a':

      • First occurrence is at position 0, and the last occurrence is at position 6.
      • Between these positions, the characters are "acbbc".
      • From these characters, you can form "aaa", "aca", and "aba" by selecting different characters between the first and last 'a'.
      • Add "aaa", "aba", and "aca" to the set.
    • For 'b':

      • First occurrence is at position 3, and the last occurrence is at position 8.
      • Between these positions, the characters are "bcac".
      • From these characters, "bbb", "bcb", and "bab" can be formed by selecting different characters between the first and last 'b'.
      • Add "bbb", "bcb", and "bab" to the set.
    • For 'c':

      • The first position of 'c' is 2, and the last is 7.
      • Between these positions, the characters are "bbca".
      • From these, "cbc", "ccc", and "cac" palindromes can be formed by selecting different characters between the first and last 'c'.
      • Add "ccc", "cbc", and "cac" to the set.
  3. After Iterating Through Relevant Characters ('a', 'b', 'c'):

    • The uniquePalindromes set contains the subsequences "aaa", "aba", "aca", "bbb", "bcb", "bab", "ccc", "cbc", and "cac".
  4. Count the Unique Palindromic Subsequences:

    • The total count of unique palindromic subsequences in the set is 9, which matches the expected output.
  5. Return the Total Count: The algorithm concludes that there are 9 unique palindromic subsequences of length 3 in "aacbbcacb", which are "aaa", "aca", "aba", "ccc", "cbc", "bbb", "bab", "cac", and "bcb".

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The overall time complexity of the algorithm is , where n is the length of the string. The loop iterates through the string 26 times for each character in the alphabet, making the complexity effectively .

Space Complexity

The space complexity of the algorithm is , where s is the number of unique palindromic subsequences that can be formed.

Unique Length-3 Palindromic Subsequences (medium)
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity